//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import React, { useEffect, useState } from "react";
import { Modal, Tabs } from "antd";
import type { ISSUE_TYPE, IssueInfo } from "@/api/project_issue";
import { ISSUE_TYPE_TASK, get as get_issue } from "@/api/project_issue";
import type { Tab } from "rc-tabs/lib/interface";
import CommentTab from "@/components/CommentEntry/CommentTab";
import { COMMENT_TARGET_BUG, COMMENT_TARGET_TASK } from "@/api/project_comment";
import CommentInModal from "@/components/CommentEntry/CommentInModal";
import EventListPanel from "./components/EventListPanel";
import { request } from "@/utils/request";
import { SubIssuePanel } from "./components/SubIssuePanel";
import { MyDependPanel } from "./components/MyDependPanel";
import { DependMePanel } from "./components/DependMePanel";
import DetailPanel from "./components/DetailPanel";
import IssueVotePanel from "./components/IssueVotePanel";
import { get_session } from "@/api/user";
import type { ProjectInfo, TagInfo } from "@/api/project";
import { type MemberInfo, list_member } from "@/api/project_member";

interface SubIssuePanelWrapProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    issueId: string;
}

const SubIssuePanelWrap = (props: SubIssuePanelWrapProps) => {
    const [issueInfo, setIssueInfo] = useState<IssueInfo | null>(null);

    const loadIssueInfo = async () => {
        const sessionId = await get_session();
        const res = await request(get_issue(sessionId, props.projectInfo.project_id, props.issueId));
        setIssueInfo(res.info);
    };

    useEffect(() => {
        if (props.issueId == "") {
            setIssueInfo(null);
        } else {
            loadIssueInfo();
        }
    }, [props.issueId]);

    return (
        <>
            {issueInfo != null && (
                <SubIssuePanel projectInfo={props.projectInfo} issueId={props.issueId} canOptSubIssue={issueInfo.user_issue_perm.can_opt_sub_issue} inModal />
            )}
        </>
    );
};

interface MyDependPanelWrapProps {
    projectInfo: ProjectInfo;
    myUserId: string;
    issueId: string;
    onClickIssue: (projectId: string, issueId: string, issueType: ISSUE_TYPE) => void;
}

const MyDependPanelWrap = (props: MyDependPanelWrapProps) => {

    const [issueInfo, setIssueInfo] = useState<IssueInfo | null>(null);

    const loadIssueInfo = async () => {
        const sessionId = await get_session();
        const res = await request(get_issue(sessionId, props.projectInfo.project_id, props.issueId));
        setIssueInfo(res.info);
    };

    useEffect(() => {
        if (props.issueId == "") {
            setIssueInfo(null);
        } else {
            loadIssueInfo();
        }
    }, [props.issueId]);
    return (
        <>
            {issueInfo != null && (
                <MyDependPanel projectInfo={props.projectInfo} issueId={props.issueId} canOptDependence={issueInfo.user_issue_perm.can_opt_dependence} inModal
                    onClickIssue={(projectId, issueId, issueType) => props.onClickIssue(projectId, issueId, issueType)} myUserId={props.myUserId}/>
            )}
        </>
    );
};

export interface IssueDetailModalProps {
    projectInfo: ProjectInfo;
    tagList: TagInfo[];
    myUserId: string;
    myDisplayName: string;
    myLogoUri: string;
    issueType: ISSUE_TYPE;
    issueId: string;
    issueTab: "detail" | "subtask" | "mydep" | "depme" | "event" | "comment" | "vote";

    onClose: () => void;
    onChange: (newTab: "detail" | "subtask" | "mydep" | "depme" | "event" | "comment" | "vote") => void;
    onClickIssue: (projectId: string, issueId: string, issueType: ISSUE_TYPE) => void;
}

const IssueDetailModal = (props: IssueDetailModalProps) => {

    const [commentDataVersion, setCommentDataVersion] = useState(0);

    const [memberList, setMemberList] = useState<MemberInfo[]>([]);

    const loadMemberList = async () => {
        const sessionId = await get_session();
        const res = await request(list_member(sessionId, props.projectInfo.project_id, false, []));
        setMemberList(res.member_list);
    };

    const calcTabItems = (): Tab[] => {
        const items: Tab[] = [
            {
                key: "detail",
                label: `${props.issueType == ISSUE_TYPE_TASK ? "任务" : "缺陷"}详情`,
                children: (
                    <div style={{ height: "calc(100vh - 320px)", overflowY: "scroll" }}>
                        {props.issueTab == "detail" && (
                            <DetailPanel projectInfo={props.projectInfo} myUserId={props.myUserId} myAdmin={props.projectInfo.user_project_perm.can_admin}
                                issueType={props.issueType} issueId={props.issueId} memberList={memberList} tagList={props.tagList}
                                onClose={() => props.onClose()} />
                        )}
                    </div>
                ),
            },
        ];
        if (props.issueType == ISSUE_TYPE_TASK) {
            items.push({
                key: "subtask",
                label: "子任务",
                children: (
                    <div style={{ height: "calc(100vh - 320px)", overflowY: "scroll" }}>
                        {props.issueTab == "subtask" && (
                            <SubIssuePanelWrap projectInfo={props.projectInfo} issueId={props.issueId} myUserId={props.myUserId}/>
                        )}
                    </div>
                ),
            });
            items.push({
                key: "mydep",
                label: "我的依赖",
                children: (
                    <div style={{ height: "calc(100vh - 320px)", overflowY: "scroll" }}>
                        {props.issueTab == "mydep" && (
                            <MyDependPanelWrap projectInfo={props.projectInfo} issueId={props.issueId}
                                onClickIssue={(projectId, issueId, issueType) => props.onClickIssue(projectId, issueId, issueType)} myUserId={props.myUserId}/>
                        )}
                    </div>
                ),
            });
            items.push({
                key: "depme",
                label: "依赖我的",
                children: (
                    <div style={{ height: "calc(100vh - 320px)", overflowY: "scroll" }}>
                        {props.issueTab == "depme" && (
                            <DependMePanel projectInfo={props.projectInfo} issueId={props.issueId} inModal
                                onClickIssue={(projectId, issueId, issueType) => props.onClickIssue(projectId, issueId, issueType)} />
                        )}
                    </div>
                ),
            });
        }
        items.push({
            key: "vote",
            label: "评估投票",
            children: (
                <div style={{ height: "calc(100vh - 320px)", overflowY: "hidden" }}>
                    {props.issueTab == "vote" && (
                        <IssueVotePanel projectInfo={props.projectInfo}
                            myUserId={props.myUserId} myDisplayName={props.myDisplayName} myLogoUri={props.myLogoUri}
                            issueId={props.issueId} />
                    )}
                </div>
            ),
        });
        items.push({
            key: "event",
            label: "操作历史",
            children: (
                <div style={{ height: "calc(100vh - 320px)", overflowY: "scroll" }}>
                    {props.issueTab == "event" && (
                        <EventListPanel projectInfo={props.projectInfo} issueType={props.issueType} issueId={props.issueId} />
                    )}
                </div>
            ),
        });
        items.push({
            key: "comment",
            label: <CommentTab projectId={props.projectInfo.project_id} targetType={props.issueType == ISSUE_TYPE_TASK ? COMMENT_TARGET_TASK : COMMENT_TARGET_BUG} targetId={props.issueId} dataVersion={commentDataVersion} />,
            children: (
                <div style={{ height: "calc(100vh - 340px)", overflowY: "scroll", paddingRight: "10px" }}>
                    <CommentInModal projectId={props.projectInfo.project_id} targetType={props.issueType == ISSUE_TYPE_TASK ? COMMENT_TARGET_TASK : COMMENT_TARGET_BUG} targetId={props.issueId}
                        myUserId={props.myUserId} myAdmin={props.projectInfo.user_project_perm.can_admin} />
                </div>
            ),
        });
        return items;
    };


    useEffect(() => {
        if (props.issueTab == "comment") {
            setTimeout(() => {
                setCommentDataVersion(oldValue => oldValue + 1);
            }, 500);
        }
    }, [props.issueTab]);

    useEffect(() => {
        loadMemberList();
    }, [props.projectInfo.project_id]);

    return (
        <Modal open title={`查看${props.issueType == ISSUE_TYPE_TASK ? "任务" : "缺陷"}`}
            width="800px" footer={null} mask={false}
            bodyStyle={{ height: "calc(100vh - 300px)", padding: "0px 10px", overflowY: "hidden" }}
            onCancel={e => {
                e.stopPropagation();
                e.preventDefault();
                props.onClose();
            }}>
            <Tabs activeKey={props.issueTab}
                onChange={key => props.onChange((key as "detail" | "subtask" | "mydep" | "depme" | "event" | "comment"))}
                tabPosition="left" size="large"
                type="card" items={calcTabItems()} />
        </Modal>
    );
};

export default IssueDetailModal;